package com.fzu.express.utils;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fzu.express.entity.WebUser;
import com.fzu.express.mapper.WebUserMapper;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Date;

/**
 * JWT工具类
 *
 * @author zyq
 * @date 2022/10/20 12:32
 **/
@Component
public class JwtUtil {

    private static WebUserMapper webUserMapper;
    @Resource
    private WebUserMapper userMapper;

    @PostConstruct
    void init() {
        webUserMapper = userMapper;
    }

    /**
     * 密钥
     */
    private static String secret = "fzu20221024";
    /**
     * 字段名
     */
    public final static String HEADER = "token";

    /**
     * @param identityId :
     * @return : java.lang.String
     * @descrition: 根据身份ID标识，生成Token
     */
    public static String getToken(String identityId) {
        Date nowDate = new Date();
        /**
         * 超时时间
         */
        long expire = 86400L;
        Date expireDate = new Date(nowDate.getTime() + expire * 1000);
        return Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setSubject(identityId)
                .setIssuedAt(nowDate)
                .setExpiration(expireDate)
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }

    /**
     * 获取 Token 中注册信息
     *
     * @param token
     */
    public static Claims getTokenClaim(String token) {
        try {
            return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    /**
     * @param expirationTime :
     * @return : boolean
     * @descrition: Token 是否过期验证
     */
    public boolean isTokenExpired(Date expirationTime) {
        return expirationTime.before(new Date());
    }

    /**
     * 根据token获取用户信息
     *
     * @param token
     * @return
     */
    public static WebUser getUser(String token) {
        Claims claim = getTokenClaim(token);
        String phone = claim.getSubject();
        LambdaQueryWrapper<WebUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WebUser::getPhone, phone);
        WebUser user = webUserMapper.selectOne(wrapper);
        if (ObjectUtils.isEmpty(user)) {
            throw new ApiException(ErrorEnum.USER_NO_EXIST);
        }
        return user;
    }
}